use std::mem::MaybeUninit;

use reqwest::Client;
use serde::{de::DeserializeOwned, Deserialize, Serialize};

use crate::error::AppErr;

static mut CLIENT: MaybeUninit<Client> = MaybeUninit::uninit();

pub fn init() {
    unsafe { CLIENT.write( Client::new() ); }
}

//const URL_IP_QUERY: &'static str = "http://ip-api.com/json/{}?lang=zh-CN";

pub async fn get<R: DeserializeOwned>(url: &str) -> Result<R, AppErr> {
    let client = unsafe { CLIENT.assume_init_ref() };
    let body = client.get(url).send().await?.json().await?;
    Ok(body)
}

#[derive(Debug, Deserialize, Serialize)]
pub struct IpInfo {
    pub status: String,
    pub country: String,

    #[serde(rename = "countryCode")]
    pub country_code: String,

    pub region: String,

    #[serde(rename = "regionName")]
    pub region_name: String,

    pub city: String,
    pub zip: String,
    pub lat: f32,
    pub lon: f32,
    pub timezone: String,
    pub isp: String,
    pub org: String,
    #[serde(rename = "as")]
    pub as_: String,
    pub query: String,
}

pub async fn get_ip_info(ip: &str) -> Result<IpInfo, AppErr> {
    let url = format!("http://ip-api.com/json/{}?lang=zh-CN", ip);
    let info: IpInfo = get(&url).await?;
    Ok(info)
}









